<script setup>
import { cloneDeep } from 'lodash-es';
import { onMounted, reactive, ref, watch, nextTick, provide } from 'vue';
import { message } from 'ant-design-vue';
import { PlusCircleOutlined } from '@ant-design/icons-vue';
import AddDepartment from './components/AddDepartment.vue';
import AddCompany from './components/AddCompany.vue';
import { getCompanyList, requireUserList,departDel} from "@/apis/organizationsManaging/unitManaging"
import utils from "@/utils"
import { useRouter } from 'vue-router';
import Pagination from "@/components/Pagination/Pagination.vue"

const router = useRouter();
const loading = ref(true);
const companyTreeData = ref([]);
const searchValue = ref("");
const columns = [
    {
        title: '序号',
        dataIndex: 'id',
        align: 'center',
        fixed: 'left',
        width: 100,
    },
    {
        title: '姓名',
        dataIndex: 'name',
        align: 'center',
        width: 100,
    },
    {
        title: '性别',
        dataIndex: 'sex',
        align: 'center',
        width: 100,
    },
    {
        title: '学历',
        dataIndex: 'education',
        align: 'center',
        width: 100,
    },
    {
        title: '所属公司',
        dataIndex: 'company',
        align: 'center',
        width: 120,
    },
    {
        title: '所属一级部门',
        dataIndex: 'depart',
        align: 'center',
        width: 120,
    },
    {
        title: '所属二级部门 ',
        dataIndex: 'subdepart',
        align: 'center',
        width: 120,
    },
    {
        title: '岗位名称',
        dataIndex: 'job',
        align: 'center',
        width: 120,
    },
    {
        title: '电话号码',
        dataIndex: 'phone',
        align: 'center',
        width: 120,
    },
    {
        title: '证件类型',
        dataIndex: 'id_type_label',
        align: 'center',
        width: 120,
    },
    {
        title: '证件号',
        dataIndex: 'id_no',
        align: 'center',
        width: 120,
    },
    {
        title: '在职状态',
        dataIndex: 'type_label',
        align: 'center',
        width: 120,
    },
    {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        fixed: 'right',
    },
];
const dataSource = ref(null);
const total = ref(0)
const formState=reactive({
    page: 1,
    size: 10,
    cid: "",
    depart_id: "",
    keyword: "",
});
const pagination = reactive({
    pageSizeOptions: ['5', '10', '20', '50'],
    showSizeChanger: true,
    total: 10,
    showTotal: total => `共 ${total} 页`
})
const departmentRef = ref(null)
const companyRef = ref(null)
const tableRef = ref(null);
const tableHeight = ref(0);
provide('companyTreeData', companyTreeData)
provide('getCompanyTreeDatalist',()=>{
    getCompanyTreeData();
})
onMounted(() => {
    nextTick(() => {
        let box = tableRef.value;
        let top = box.children[0].getBoundingClientRect().top;
        tableHeight.value = window.innerHeight - top -80-80;
    })
})
onMounted(async () => {
    await getCompanyTreeData();
    if (companyTreeData.value.length > 0) {
        formState.cid=companyTreeData.value[0].id;
        getDataSource();
    } else {
        loading.value = false
    }
})
const getCompanyTreeData = () => {
    return new Promise((resolve, reject) => {
        getCompanyList().then(res => {
            if (res.code === 1) {
                companyTreeData.value = generateData(res.data.compays);
                resolve()
            } else {
                message.error(res.msg);
            }
        })
    })
};
const generateData = (options) => {
    // console.log(options);
    let list = []
    for (let i = 0; i < options.length; i++) {
        const children = [];
        let obj = {
            title: options[i].name,
            tel: options[i].tel,
            id: options[i].id,
            pid: options[i].pid,
            key: options[i].name +':'+ options[i].id,
            description:options[i].description,
        };
        options[i].type&&(obj.type=options[i].type)
        options[i].cid&&(obj.cid=options[i].cid)
        if (options[i].departs && options[i].departs.length > 0) {
            (obj.children = generateData(options[i].departs))
        }
        list.push(obj)
    }
    return list;

};
const onSelect = (keys, e) => {
    if(!e.selectedNodes[0]) return;
    if(e.selectedNodes[0].cid&&e.selectedNodes[0].cid!=0){
        formState.cid=e.selectedNodes[0].cid;
        formState.depart_id=e.selectedNodes[0].id;
    }else{
        formState.cid=e.selectedNodes[0].id;
        formState.depart_id="";
    }
    getDataSource();
};
const getDataSource = () => {
    requireUserList(formState).then(res => {
        if (res.code === 1) {
            dataSource.value = res.data.list;
            total.value = res.data.total;
            loading.value = false;
        } else {
            loading.value = false;
            dataSource.value = [];
            pagination.total = 0;
            message.error(res.msg);
        }
    })
};
const handAddDepartment = () => {
    departmentRef.value.open = true;
}
const handAddCompany = () => {
    companyRef.value.open = true;
}
const operatingRecord = (options) => {
    router.push({ path: `/organizations-managing/unit-managing-info/${options.id}` })
}
const changepage=(options)=>{
    loading.value=true;
    formState.page=options.page;
    formState.size=options.pageSize;
    getDataSource();
}
const handleEdit=(data)=>{
    !data.cid?companyEdit(data):departmentEdit(data);
}
const handleDelete=(data)=>{
    if(!data.cid){
        message.warning('公司暂不支持删除');
        return
    }
    console.log(data);
    departDel({id:data.id}).then(res=>{
        if(res.code===1){
            getCompanyTreeData();
        }else{
            message.error(res.msg);
        }
    })

}
// 公司编辑
const companyEdit=(data)=>{
    companyRef.value.formState.id=data.id;
    companyRef.value.formState.name=data.title;
    companyRef.value.formState.tel=data.tel&&"";
    companyRef.value.formState.description=data.description;
    companyRef.value.formState.type=data.type;
    data.pid!==0?(companyRef.value.formState.pid=data.pid):(companyRef.value.formState.pid="")
    companyRef.value.open = true;
    console.log(data);
}
// 部门编辑
const departmentEdit=(data)=>{
    console.log("部门编辑");
    departmentRef.value.formState.id=data.id;
    departmentRef.value.formState.name=data.title;
    departmentRef.value.formState.tel=data.tel||"";
    departmentRef.value.formState.description=data.description;
    departmentRef.value.formState.cid=data.cid;
    data.pid!==0?(departmentRef.value.formState.pid=data.pid):(departmentRef.value.formState.pid="")
    departmentRef.value.open = true;
    console.log(data);
}
</script>
<template>
    <!-- 单元管理 -->
    <div class="unit-managing">
        <div class="unit-tree">
            <a-input v-model:value="searchValue" style="margin-bottom: 8px" placeholder="请输入" :allowClear="true" />
            <a-skeleton v-if="companyTreeData.length===0"/>
            <div ref="tableRef"> 
                <a-tree  v-if="companyTreeData.length" :tree-data="companyTreeData" :default-expandAll="true" @select="onSelect" >
                    <template #title="data">
                        <span v-if="data.title.indexOf(searchValue) > -1">
                            {{ data.title.substr(0, data.title.indexOf(searchValue)) }}
                            <span style="color: var(--themeColor);font-weight:800;">{{ searchValue }}</span>
                            {{ data.title.substr(data.title.indexOf(searchValue) + searchValue.length)}}
                        </span>
                        <span v-else>{{ data.title }}</span>
                        <a-dropdown placement="bottomRight" :trigger="'click'">
                            <img src="@/assets/images/more.svg" alt="" @click.stop="">
                            <template #overlay>
                                <a-menu>
                                    <a-menu-item key="0" @click="handleEdit(data)">
                                        编辑
                                    </a-menu-item>
                                    <a-menu-item key="1" @click="handleDelete(data)">
                                        删除
                                    </a-menu-item>
                                </a-menu>
                            </template>
                        </a-dropdown>
                    </template>
                </a-tree>
            </div>
        </div>
        <div class="unit-table">
            <div class="table-search">
                <a-button type="primary" @click="handAddCompany">
                    <template #icon>
                        <PlusCircleOutlined />
                    </template>
                    创建公司
                </a-button> &nbsp;
                <a-button type="primary" @click="handAddDepartment">
                    <template #icon>
                        <PlusCircleOutlined />
                    </template>
                    创建部门
                </a-button>
            </div>
            <div class="table-box" ref="tableRef">
                <a-table :loading="loading" :columns="columns" :data-source="dataSource" rowKey="id"
                :pagination="false" :scroll="{ x: 'max-content',y:tableHeight}">
                    <template #bodyCell="{ column, text, record }">
                        <template v-if="column.dataIndex === 'sex'">
                            <div>
                                {{ text === 1 ? '男' : '女' }}
                            </div>
                        </template>
                        <template v-else-if="column.dataIndex === 'operation'">
                            <div>
                                <!-- <a-button type="link" size="small">重新编辑</a-button>
                                <a-button type="link" size="small" danger>删除</a-button> -->
                                <a-button type="link" size="small" @click="operatingRecord(record)">操作记录</a-button>
                            </div>
                        </template>
                        <!-- <template v-else-if="column.dataIndex === 'id'">
                            <div>
                                {{ text }}000000000000000000000000000000000000000000
                            </div>
                        </template> -->
                    </template>
                </a-table>
            </div>
            <Pagination :total="total" :page="formState.page" :size="formState.size" @changepage="changepage"/>
        </div>
        <AddDepartment ref="departmentRef" />
        <AddCompany ref="companyRef" />
    </div>
</template>
<style lang='scss' scoped>
.unit-managing {
    width: 100%;
    display: flex;
    height: 100%;

    .unit-tree {
        width: 20%;
        min-width: 300px;
        margin-right: 10px;
        background: var(--fff-141414-color);
        padding: 15px;
        display: flex;
        flex-direction: column;

        &>div {
            &:nth-child(2) {
                overflow: auto;
            }
        }

    }

    .unit-table {
        display: flex;
        width: calc(100% - 20% - 10px);
        min-width: 800px;
        background: var(--fff-141414-color);
        padding: 15px;
        display: flex;
        flex-direction: column;
        .table-search {
            margin-bottom: 10px;
        }
        .table-box{
            flex: 1;
        }

        &>div {
            &:nth-child(2) {
                flex: 1;
            }
        }
    }

    .tree-title {
        display: flex;
        justify-content: space-between;
    }
}

:deep(.ant-tree-treenode) {
    width: 100%;
}

:deep(.ant-tree-node-content-wrapper) {
    flex: 1;
    display: flex;
}

:deep(.ant-tree-title) {
    flex: 1;
    display: flex;
    align-items: center;

    img {
        margin-left: auto;
        margin-right: 15px;
    }
}
</style>